/*
 * facecloud后台api页面
 * @Author: ljb
 * @Date: 2018-03-26 10:18:23
 * @Last Modified by: ljb
 * @Last Modified time: 2019-11-19 09:14:28
 */
<style lang="less" rel="stylesheet/less" type="text/less">
.api-box {
  font-size: 20px;
  width: 500px;
  .api-text {
    font-size: 16px;
  }
  .try-out {
    margin-left: 50px;
  }
  .radio-tips {
    color: red;
  }
}
</style>
<template>
  <div class="api-box">
    <Form ref="formData" :model="form_data" :rules="ruleInline">
      <Form-item label="应用名称" prop="name">
        <Input v-model="form_data.name" name="app-name" type="text"></Input>
      </Form-item>
      <FormItem label="应用描述" prop="description">
        <Input v-model="form_data.description" :autosize="{minRows: 3,maxRows: 5}" type="textarea"></Input>
      </FormItem>
      <Form-item>
        <div class="api-text">资费方案</div>
        <RadioGroup v-model="form_data.type" size="large">
          <Radio label="测试" />
          <Radio label="按次计费" class="try-out" />
          <div class="radio-tips">*如需开通按时间段计费和永久授权的ApiKey请联系商务处理</div>
          <!-- <Radio
						label="按时间段计费"
						class="try-out"

					/>
					<Radio
						label="永久授权"
						class="try-out"

          />-->
        </RadioGroup>
      </Form-item>

      <!-- 开始时间 -->

      <!-- <Form-item
				v-if="form_data.type==='按时间段计费'"

				label="开始时间"
				prop="started_at"
			>
				<DatePicker
					v-model="form_data.started_at"
					:style="{width: '260px'}"
					:options="startOption"
					placeholder="请输入开始时间"
					type="datetime"
					placement="top"
					name="create-started_at"
					@on-change="changeSTDate"/>
			</Form-item>

      <!-- 结束时间-->
      <!-- <Form-item
				v-if="form_data.type==='按时间段计费'"

				label="结束时间"
				prop="ended_at"
			>
				<DatePicker
					v-model="form_data.ended_at"
					:style="{width: '260px'}"
					:options="endOption"
					placeholder="请输入结束时间"
					type="datetime"
					placement="top"
					name="create-ended_at"
					@on-change="changeEDDate"/>
      </Form-item>-->
      <!-- <Form-item
				v-if="form_data.type==='按时间段计费'"
				label="开始时间与结束时间"
				props="start_end"
			>
				<DatePicker
					v-model="form_data.start_end"
					:options="startOption"
					:style="{width: '260px'}"
					:time-picker-options="disabledTime"
					type="datetimerange"
					placement="top"
					placeholder="请选择开始时间与结束时间"
					@on-change="changeEDDate"
      />-->
      <!-- </Form-item> -->
      <Form-item>
        <Button
          size="large"
          type="primary"
          name="create__submit"
          @click="handleSubmit('formData')"
        >创建</Button>
      </Form-item>
    </Form>
  </div>
</template>

<script type="text/babel">
import qs from "qs";
import { deleteEmptyValue } from "../../../utils";

export default {
  data() {
    const validateNull = (rule, value, callback) => {
      if (!value) {
        if (rule.field == "name") {
          return callback(new Error("名称不能为空!"));
        }
        return callback(new Error("描述不能为空!"));
      }
      if (/\s/.test(value)) {
        if (rule.field == "name") {
          return callback(new Error("名称不能为存在空格!"));
        }
        return callback(new Error("描述不能存在空格!"));
      }
      callback();
    };
    return {
      // real_started_at: null,
      // real_ended_at: null,
      // changeDate: null,
      // startOption: {
      // 	disabledDate(date) {
      // 		return date && date.valueOf() < Date.now() - 86400000;
      // 	},
      // },

      form_data: {
        // ended_at: null,
        // started_at: null,
        name: "",
        description: "",
        type: "测试"
        // start_end: [],
      },
      ruleInline: {
        name: [
          {
            validator: validateNull,
            required: true,
            trigger: "blur,change"
          }
        ],
        description: [
          {
            required: true,
            validator: validateNull,
            trigger: "blur,change"
          }
        ]
        // start_end: [
        // 	{
        // 		required: true,
        // 		message: '时间是必须的',
        // 		trigger: 'blur,change',
        // 	},
        // ],
        // started_at: [
        // 	{
        // 		required: true,
        // 		type: 'date',
        // 		message: '开始时间是必须的',
        // 		trigger: 'blur,change',
        // 	},
        // ],
        // ended_at: [
        // 	{
        // 		required: true,
        // 		type: 'date',
        // 		message: '结束时间是必须的',
        // 		trigger: 'blur,change',
        // 	},
        // ],
      }
    };
  },
  computed: {
    /**
     *限制不能选择的时间
     */
    // disabledTime() {
    // 	const option = {};
    // const nowDate = new Date(); // 实例一个时间对象；
    // const nowHours = nowDate.getHours(); // 时
    // const nowMin = nowDate.getMinutes(); // 分
    // const nowDay = nowDate.getDate(); // 日
    // const nowYear = nowDate.getFullYear(); // 获取系统的年；
    // const nowMouth = nowDate.getMonth() + 1; // 获取系统月份，由于月份是从0开始计算，所以要加1
    // const emtyHours = [];
    // const emtyMinutes = [];
    // for (let index = 0; index < nowHours; index++) {
    // 	emtyHours.push(index);
    // }
    // for (let index = 0; index < nowMin; index++) {
    // 	emtyMinutes.push(index);
    // }
    // console.log('this.changeDate', this.changeDate);
    // if (`${nowYear}-${nowMouth}-${nowDay}` === this.changeDate) {
    // 	 option = {
    // 		disabledHours: emtyHours,
    // 		disabledMinutes: emtyMinutes,
    // 	};
    // }
    // 	return option;
    // },
  },
  methods: {
    // changeSTDate(date) {
    // 	this.real_started_at = this.$moment(date).utc().format();
    // 	console.log(this.real_started_at);

    // },

    // changeEDDate(date) {
    // this.changeDate = date[0].slice(0, 10);
    // 	if (date[0] === '') {
    // 		this.real_started_at = null;
    // 		this.real_ended_at = null;
    // 	} else {
    // 		this.real_started_at = this.$moment(date[0]).utc().format();
    // 		this.real_ended_at = this.$moment(date[1]).utc().format();
    // 	}

    // },
    handleSubmit(name) {
      // if (this.form_data.start_end[0] === '' && this.form_data.type === '按时间段计费') {
      // 	this.$Message.error('开始时间与结束时间不能为空!');
      // } else {
      this.$refs[name].validate(valid => {
        if (valid) {
          // 创建APIkey请求
          this.$Spin.show();
          this.APICreate(name);
        } else {
          this.$Message.error("你输入的信息有误");
        }
      });
      // }
    },

    APICreate(param) {
      let newData = new Object();
      newData.name = this.form_data.name;

      newData.description = this.form_data.description;

      newData.type = this.form_data.type;

      if (newData.type === "测试") {
        newData.type = 0;
      } else if (newData.type === "按次计费") {
        newData.type = 1;
      }
      // else if (newData.type === '按时间段计费') {
      // 	newData.type = 2;
      // 	newData.start_time = this.real_started_at;

      // 	newData.end_time = this.real_ended_at;
      // } else {
      // 	newData.type = 3;
      // }

      newData.token = sessionStorage.getItem("token");

      newData = deleteEmptyValue(newData);

      this.axios
        .post(
          `${window.location.origin}/admin/api/v1/apikey/create`,
          qs.stringify(newData)
        )
        .then(({ data }) => {
          if (data.code === 200) {
            this.$refs[param].resetFields();
            this.form_data.type = "测试";
            this.form_data.start_end = null;
            this.$Message.success("创建成功");
            this.$Spin.hide();
          } else if (data.code === 7003) {
            this.$Message.error({
              content: "token验证失败,过期或token错误,请重新登录",
              duration: 5,
              closable: true
            });
            this.$router.push({
              path: "/login"
            });
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
          this.$refs[param].resetFields();
          this.form_data.type = "测试";
        });
    }
  }
};
</script>
